﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace SFP.Animation2D
{
    public class Fader
    {
        public const int FADE_IN = 0;
        public const int FADE_OUT = 1;

        public double FadeTime { get; set; }
        private double _fadeAmount;
        public double FadeAmount
        {
            get
            {
                return _fadeAmount;
            }

            set
            {
                _fadeAmount = value;
                if (_fadeAmount < 0) _fadeAmount = 0;
                if (_fadeAmount > 1) _fadeAmount = 1;

                fadeAlpha = (int)(255 * _fadeAmount);
            }
        }

        private Game game;
        private int fadeType = FADE_IN;
        private int fadeAlpha = 0;
        private bool isFading = false;
        private double passedFadeTime = 0;

        public Fader(Game game, double fadeTime)
        {
            this.game = game;
            FadeTime = fadeTime;
        }

        public void startFading(int fadeType)
        {
            if (isFading) return;

            this.fadeType = fadeType;
            passedFadeTime = 0;
            isFading = true;
        }

        public void resetFading()
        {
            isFading = false;
            passedFadeTime = 0;
            fadeAlpha = 0;
        }

        public void update(double time)
        {
            if (!isFading) return;

            if (fadeType == FADE_IN)
            {
                passedFadeTime += time;
                FadeAmount = 1 - passedFadeTime / FadeTime;
            }
            else if (fadeType == FADE_OUT)
            {
                passedFadeTime += time;
                FadeAmount = passedFadeTime / FadeTime;
            }

            if (passedFadeTime >= FadeTime) isFading = false;
        }

        public void draw(Graphics g)
        {
            g.FillRectangle(new SolidBrush(Color.FromArgb(fadeAlpha, Color.Black)), new Rectangle(new Point(0, 0), game.resolution));
        }
    }
}
